package dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import pojo.Loaisanpham;
import pojo.Sanpham;
import util.ConvertHelper;
import util.HibernateUtil;
import util.IVisitor;

public class SanphamDAO extends AbstractDAO<Sanpham, Integer>{


	@Override
	protected Class getPOJOClass() {
		// TODO Auto-generated method stub
		return Sanpham.class;
	}

	@Override
	protected Query MakeHQL() {
		// TODO Auto-generated method stub
		return null;
	}
		
	
	// Hàm này đúng, nhưng không cần thiết vì đã có hàm get()
	/*public Sanpham LaySanPhamTheoMaSP(int masp) throws HibernateException{
        Session session = HibernateUtil.getSessionFactory().openSession();
        String hql = "from Sanpham sp where sp.masanpham=:masp";
        Query query = session.createQuery(hql);
        query.setInteger("masp", masp);

        Sanpham sanpham = (Sanpham)query.uniqueResult();
       
        session.close();
        
        return sanpham;
    }*/
    
    public List<Sanpham> LaySanPhamCungLoai(int maloaisp, int soluong) throws HibernateException{
        Session session = HibernateUtil.getSessionFactory().openSession();
        String hql = "select sp.masanpham, sp.tensanpham, sp.hinhanh, sp.giaban from Sanpham sp where sp.loaisanpham.maloaisanpham=:maloaisp";
        Query query = session.createQuery(hql);
        query.setInteger("maloaisp", maloaisp);
        
        List<Sanpham> list = session.createCriteria(Sanpham.class).setMaxResults(soluong).list();
        session.close();
        return list;
    }
    
   /* public List<Sanpham> LayNSPMoiNhat(int n) throws HibernateException{
        Session session = HibernateUtil.getSessionFactory().openSession();
        String hql = "select sp.tensanpham, sp.hinhanh, sp.mota, sp.giaban from Sanpham sp order by sp.ngaynhansanpham desc";
        Query query = session.createQuery(hql);
        List<Sanpham> list = session.createCriteria(Sanpham.class).setMaxResults(n).list();
        session.close();
        return list;
    }
    
    public List<Sanpham> LayNSPBanChayNhat(int n) throws HibernateException{
        Session session = HibernateUtil.getSessionFactory().openSession();
        String hql = "select sp.tensanpham, sp.hinhanh, sp.mota, sp.giaban from Sanpham sp order by sp.soluongban desc";
        Query query = session.createQuery(hql);
        List<Sanpham> list = session.createCriteria(Sanpham.class).setMaxResults(n).list();
        session.close();
        return list;
    }*/
    
    public List<Sanpham> LayDanhSachSanPham(int soluong, String cotsapxep, String trattu) throws HibernateException{
        Session session = HibernateUtil.getSessionFactory().openSession();
        String hql = String.format("select sp from Sanpham sp order by sp.%s %s", cotsapxep, trattu);
        
        //List<Sanpham> list = session.createCriteria(Sanpham.class).setMaxResults(soluong).list();
        List<Sanpham> list = session.createQuery(hql).setMaxResults(soluong).list();
        session.close();
        return list;      
    } 
	
	/*
	private static SessionFactory sessionFactory;
	private static ServiceRegistry serviceRegistry;

	public static Sanpham layThongTinSanPham(String maSP) {
		Session session = null;
		Sanpham sp = null;
		try {
			try {
				Configuration cfg = new Configuration();

				cfg.addResource("pojo/Binhluan.hbm.xml").configure();
				cfg.addResource("pojo/Chitietgiohang.hbm.xml").configure();
				cfg.addResource("pojo/Chitiethoadon.hbm.xml").configure();
				cfg.addResource("pojo/Giohang.hbm.xml").configure();
				cfg.addResource("pojo/Hinhthucthanhtoan.hbm.xml").configure();
				cfg.addResource("pojo/Hoadon.hbm.xml").configure();
				cfg.addResource("pojo/Loaisanpham.hbm.xml").configure();
				cfg.addResource("pojo/Makiemtra.hbm.xml").configure();
				cfg.addResource("pojo/Nhasanxuat.hbm.xml").configure();
				cfg.addResource("pojo/Nhomsanpham.hbm.xml").configure();
				cfg.addResource("pojo/Quangcao.hbm.xml").configure();
				cfg.addResource("pojo/Sanpham.hbm.xml").configure();
				cfg.addResource("pojo/Taikhoan.hbm.xml").configure();
				cfg.addResource("pojo/Thamsochung.hbm.xml").configure();

				serviceRegistry = new ServiceRegistryBuilder().applySettings(
						cfg.getProperties()).buildServiceRegistry();

				sessionFactory = cfg.buildSessionFactory(serviceRegistry);
			} catch (Throwable ex) {
				System.err.println("Failed to create sessionFactory object."
						+ ex);
				throw new ExceptionInInitializerError(ex);
			}

			session = sessionFactory.openSession();

			String hql = "select sp.masanpham,sp.manhasanxuat, sp.maloaisanpham, "
					+ "sp.tensanpham, sp.giaban, sp.soluotxem, sp.soluongban, sp.mota, "
					+ "sp.xuatxu, sp.ngaynhansanpham, sp.daxoa, sp.hinhanh"
					+ " from Sanpham sp" + " where sp.masanpham = " + maSP;

			Query selectClause = session.createQuery(hql);
			List<Object> ds = selectClause.list();

			// sp = ConvertHelper.ConvertObjectToSanPham((Object[]) ds.get(0));
			sp = new Sanpham((Object[]) ds.get(0));

			System.out.println(sp.getManhasanxuat());

		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			session.close();
		}

		return sp;
	}
	*/

	public List<Sanpham> GetSanPhamTheoMaLoai(int maLoaiSanPham) {
		
		if (-1 == maLoaiSanPham)
			return getList();		
		
		String hql = "select sp from Sanpham sp " +
				"where sp.loaisanpham.maloaisanpham = " + maLoaiSanPham;
		
		System.out.println(hql);
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		Query selectClause = session.createQuery(hql);
		
		List<Sanpham> lstSanPham = selectClause.list();

		System.out.println(lstSanPham.size());
		session.close();
		return lstSanPham;
	}
	
	public List<Sanpham> GetSanPhamTheoMaNhom(int maNhomSanPham, Integer from, Integer max) {
		String hql = "select sp from Sanpham sp, Loaisanpham lsp " +
				"where sp.loaisanpham.maloaisanpham = lsp.maloaisanpham and lsp.nhomsanpham.manhom = " + maNhomSanPham;
		
		System.out.println(hql);
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		Query selectClause = session.createQuery(hql);
		selectClause.setFirstResult(from);
		selectClause.setMaxResults(max);
		List<Sanpham> lstSanPham = selectClause.list();
		session.close();
		return lstSanPham;
	}
	public List<Sanpham> GetSanPhamTheoMaNhaSanXuat(int maNhaSanXuat, Integer from, Integer max) {
		String hql = "select sp from Sanpham sp " +
				"where sp.nhasanxuat.manhasanxuat = " + maNhaSanXuat;
		
		System.out.println(hql);
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		Query selectClause = session.createQuery(hql);
		selectClause.setFirstResult(from);
		selectClause.setMaxResults(max);
		List<Sanpham> lstSanPham = selectClause.list();
		session.close();
		return lstSanPham;
	}
	
	public int CountSanPhamTheoMaNhom(int maNhomSanPham)
	{
		String hql = "select count(*) from Sanpham sp, Loaisanpham lsp " +
				"where sp.loaisanpham.maloaisanpham = lsp.maloaisanpham and lsp.nhomsanpham.manhom = " + maNhomSanPham;
		
		System.out.println(hql);
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		Query selectClause = session.createQuery(hql);
		int count = Integer.parseInt(selectClause.list().get(0).toString());

		session.close();
		return count;
	}
	public int CountSanPhamTheoMaNhaSanXuat(int maNhaSanXuat)
	{
		String hql = "select count(*) from Sanpham sp " +
				"where sp.nhasanxuat.manhasanxuat = " + maNhaSanXuat;
		
		System.out.println(hql);
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		Query selectClause = session.createQuery(hql);
		int count = Integer.parseInt(selectClause.list().get(0).toString());

		session.close();
		return count;
	}
	
	public List<Sanpham> SearchSanPham(int from, int max, String tensanpham, String maloaisanpham, String manhasanxuat, String giatu, String giaden)
	{
		if(tensanpham == null)
			tensanpham = "sp.tensanpham";	
		else
			tensanpham = "%" + tensanpham.toLowerCase()	+ "%";
		
		if(maloaisanpham.equals("-1"))
			maloaisanpham = "sp.loaisanpham.maloaisanpham";	
		
		if(manhasanxuat.equals("-1"))
			manhasanxuat = "sp.nhasanxuat.manhasanxuat";	
		
		String hql = String.format("select sp from Sanpham sp " +
				"where lower(sp.tensanpham) like :searchKey and " +
				"sp.loaisanpham.maloaisanpham = %s and " +
				"sp.nhasanxuat.manhasanxuat = %s and " +
				"sp.giaban >= %s and sp.giaban <= %s", maloaisanpham, manhasanxuat, giatu, giaden);
		
		System.out.println(hql);
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		Query selectClause = session.createQuery(hql);
		selectClause.setParameter("searchKey", tensanpham);
		selectClause.setFirstResult(from);
		selectClause.setMaxResults(max);
		
		List<Sanpham> result = selectClause.list();

		session.close();
		
		return result;
	}
	
	public int CountSearchSanPham(String tensanpham, String maloaisanpham, String manhasanxuat, String giatu, String giaden)
	{
		if(tensanpham == null)
			tensanpham = "sp.tensanpham";	
		else
			tensanpham = "%" + tensanpham.toLowerCase()	+ "%";
		
		if(maloaisanpham.equals("-1"))
			maloaisanpham = "sp.loaisanpham.maloaisanpham";	
		
		if(manhasanxuat.equals("-1"))
			manhasanxuat = "sp.nhasanxuat.manhasanxuat";	
		
		String hql = String.format("select count(*) from Sanpham sp " +
				"where lower(sp.tensanpham) like :searchKey and " +
				"sp.loaisanpham.maloaisanpham = %s and " +
				"sp.nhasanxuat.manhasanxuat = %s and " +
				"sp.giaban >= %s and sp.giaban <= %s", maloaisanpham, manhasanxuat, giatu, giaden);
		
		System.out.println(hql);
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		Query selectClause = session.createQuery(hql);
		selectClause.setParameter("searchKey", tensanpham);
		
		int result = Integer.parseInt(selectClause.list().get(0).toString());

		session.close();
		
		System.out.println("So luong trang trong CountSearchSanPham: " + result);
		
		return result;
	}
	
    //---------------QNReck Visitor Template-----------
    public void accept(IVisitor visitor, String searchKey, Integer from, Integer max)
    {
    	visitor.accept(this, searchKey, from, max);
    }
	
}
